import React, { Component, Suspense } from 'react';
import { connect } from 'dva';
import {
  Row,
  Col,
  Input,
  Button,
  Table,
  Card,
  message,
  Icon,
  Pagination,
  Radio,
  Form,
  Modal,
  Spin,
  Switch,
} from 'antd';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import { FormattedMessage } from 'umi-plugin-react/locale';
import moment from 'moment';
const confirm = Modal.confirm;
import PageLoading from '@/components/PageLoading';
import styles from './index.less';

const Search = Input.Search;
const CollectionCreateForm = Form.create({ name: 'form_in_modal' })(
  class extends React.Component {
    checkField = (rule, value, callback) => {
      const reg = /^[0-9a-zA-Z_@.]{1,}$/g;
      if (rule.field === 'userGuest') {
        if (value) {
          if (reg.test(value)) {
            if (value.length > 30 || value.length < 6) {
              callback('支持6-30位大小写字母、数字和下划线');
            } else {
              callback();
            }
          } else {
            callback('支持6-30位大小写字母、数字和下划线');
          }
        } else {
          callback('支持6-30位大小写字母、数字和下划线');
        }
      }
      if (rule.field === 'password') {
        if (value) {
          if (value.length < 6) {
            callback('密码长度需大于6位');
          } else {
            callback();
          }
        }
      }
      // if(rule.field ==='newPassword') {
      //   const form = this.formRef.props.form;
      //   if (value && value !== form.getFieldValue('password')) {
      //     callback('请确认您的密码');
      //   } else {
      //     callback();
      //   }
      // }
    };

    render() {
      const { visible, onCancel, onCreate, form, userInfo, isEdit, loading } = this.props;
      const { getFieldDecorator } = form;
      const formItemLayout = {
        labelCol: {
          xs: { span: 24 },
          sm: { span: 5 },
        },
        wrapperCol: {
          xs: { span: 24 },
          sm: { span: 15 },
        },
      };
      return (
        <Modal
          visible={visible}
          title="添加编辑机器人"
          okText="保存"
          onCancel={onCancel}
          onOk={onCreate}
        >
          <Spin spinning={loading}>
            <Form {...formItemLayout}>
              <Form.Item label="机器人名称">
                {getFieldDecorator('gender', {
                  validateTrigger: ['onChange', 'onBlur'],
                  initialValue: userInfo.gender ? userInfo.gender : '',
                  rules: [{ required: true, message: '请输入机器人名称' }],
                })(<Input placeholder="请输入机器人名称" />)}
              </Form.Item>
              <Form.Item label="登录用户名">
                {getFieldDecorator('userGuest', {
                  validateTrigger: ['onChange', 'onBlur'],
                  initialValue: userInfo.userGuest ? userInfo.userGuest : '',
                  rules: [
                    { required: true, message: '请输入登录用户名' },
                    {
                      validator: this.checkField,
                    },
                  ],
                })(<Input placeholder="请输入登录用户名" />)}
              </Form.Item>
              <Form.Item label="用户昵称">
                {getFieldDecorator('nick', {
                  initialValue: userInfo.nick ? userInfo.nick : '',
                })(<Input placeholder="请输入用户昵称" />)}
              </Form.Item>
              <Form.Item label="登录密码">
                {getFieldDecorator('password', {
                  validateTrigger: ['onChange', 'onBlur'],
                  initialValue: userInfo.password ? userInfo.password : '',
                  rules: [
                    { required: true, message: '请输入登录密码' },
                    {
                      validator: this.checkField,
                    },
                    { pattern: /^[^\s]*$/, message: '请勿输入空格' },
                  ],
                })(<Input.Password placeholder="请输入登录密码" autoComplete="new-password" />)}
              </Form.Item>
              <Form.Item label="确认密码">
                {getFieldDecorator('newPassword', {
                  validateTrigger: ['onChange', 'onBlur'],
                  initialValue: userInfo.newPassword ? userInfo.newPassword : '',
                  rules: [{ required: true, message: '请输入登录密码' }],
                })(<Input.Password placeholder="请输入登录密码" autoComplete="new-password" />)}
              </Form.Item>
            </Form>
          </Spin>
        </Modal>
      );
    }
  }
);

@connect(({ robotManage, loading }) => ({
  robotManage,
  loading: loading.effects['robotManage/getUsers'],
}))
class RobotManage extends Component {
  constructor(props) {
    super(props);
    this.state = {
      page: 1,
      notices: [],
      tableLoading: true,
      total: 0,
      visible: false,
      searchText: '',
      userInfo: {},
      isEdit: false,
      loading: true,
      pageSize: 10,
      auth: true,
      jy: false,
      isLoading:false
    };
    this.columns = [
      {
        key: 'name',
        align: 'left',
        title: '机器人昵称',
        dataIndex: 'name',
      },
      {
        key: 'guest',
        align: 'left',
        title: '用户名',
        dataIndex: 'guest',
      },
      {
        key: 'disabled',
        align: 'left',
        title: '状态',
        dataIndex: 'disabled',
        render: dataIndex => {
          return <div>{!dataIndex ? '启用' : '停用'}</div>;
        },
      },
      // {
      //   key: 'rolesDes',
      //   align: 'left',
      //   title: '用户角色',
      //   dataIndex: 'rolesDes',
      // },
      // {
      //   key: 'departmentName',
      //   align: 'left',
      //   title: '所属业务',
      //   dataIndex: 'departmentName',
      // },
      {
        key: 'addTime',
        align: 'left',
        title: '创建时间',
        dataIndex: 'addTime',
        render: dataIndex => {
          return moment(parseInt(dataIndex)).format('YYYY-MM-DD HH:mm:ss');
        },
      },
      {
        title: '操作',
        align: 'left',
        render: (text, row) => {
          return (
            <div>
              {row.disabled ? (
                <Button
                  type="primary"
                  icon="pause"
                  htmlType="button"
                  size="small"
                  disabled={row.guest === 'systemAdmin'}
                  style={this.qwe(row)}
                  onClick={() => this.editUser(row)}
                >
                  启用
                </Button>
              ) : (
                <Button
                  icon="caret-right"
                  htmlType="button"
                  type="danger"
                  size="small"
                  disabled={row.guest === 'systemAdmin'}
                  style={this.qwe(row)}
                  onClick={() => this.editUser(row)}
                >
                  停用
                </Button>
              )}
              <Button
                disabled={this.todo(row)}
                type="danger"
                icon="close"
                htmlType="button"
                size="small"
                disabled={row.guest === 'systemAdmin'}
                style={this.qwe(row)}
                onClick={() => this.showDeleteConfirm(row)}
              >
                删除
              </Button>
              <Button
                disabled={row.guest === 'systemAdmin'}
                icon="compass"
                htmlType="button"
                size="small"
                style={this.qwe(row)}
                onClick={() => this.getRobotToken(row)}
              >
                查看
              </Button>
            </div>
          );
        },
        width: '300px',
      },
    ];
  }

  componentDidMount() {
    this.getUsers();
    const { currentUser } = this.state;
  }

  showModal = () => {
    const form = this.formRef.props.form;
    form.resetFields();
    this.setState({ visible: true, loading: false, userInfo: {} });
  };

  handleCancel = () => {
    const form = this.formRef.props.form;
    form.resetFields();
    this.setState({ visible: false, isEdit: false });
  };

  handleCreate = () => {
    const form = this.formRef.props.form;
    const type = this.state.isEdit;
    form.validateFields((err, values) => {
      if (err) {
        return;
      }

      if (values.password !== values.newPassword) {
        return message.error('两次输入的密码不一致，请重新输入');
      }

      this.addUser(values);
    });
  };

  saveFormRef = formRef => {
    this.formRef = formRef;
  };

  onChangeForPage = number => {

    this.setState(
      {
        page: number,
        tableLoading: true,
      }
      // () => {
      //   this.getUsers();
      // }
    );
  };

  onShowSizeChangeForPage = (current, size) => {
    this.setState(
      {
        page: current,
        pageSize: size,
        tableLoading: true,
      }
      // () => {
      // this.getUsers();
      // }
    );
  };

  getUsers = () => {
    const { dispatch, currentUser } = this.props;
    dispatch({
      type: 'robotManage/getUsers',
      payload: { userId: currentUser.uid, robotName: this.state.searchText },
      callback: res => {

        this.setState({
          notices: res.list,
          tableLoading: false,
          total: res.total,
        });
      },
    });
  };

  addUser = obj => {
    const form = this.formRef.props.form;
    const { dispatch, currentUser } = this.props;
    dispatch({
      type: 'robotManage/addUser',
      payload: {
        password: obj.password,
        userId: currentUser.uid,
        userGuest: obj.userGuest,
        robotName: obj.gender,
        nick: obj.nick
      },
      callback: res => {
        //  if(!res.code){
        message.info(res.msg);
        form.resetFields();
        this.setState({ visible: false });
        return this.getUsers();
        //  }
      },
    });
  };

  delUser = row => {
    const { dispatch, currentUser } = this.props;
    dispatch({
      type: 'robotManage/delUser',
      payload: { robotId: row.id, userId: currentUser.uid },
      callback: res => {
        message.info(res.msg);
        this.getUsers();
      },
    });
  };

  showDeleteConfirm = row => {
    const that = this;
    confirm({
      title: '确认删除【' + row.name + '】该机器人么',
      content: '',
      okText: '确定',
      okType: 'danger',
      cancelText: '取消',
      onOk() {

        that.delUser(row);
      },
      onCancel() {

      },
    });
  };

  resetUser = row => {
    const { dispatch } = this.props;
    dispatch({
      type: 'robotManage/resetUser',
      payload: { userId: row._id },
      callback: res => {
        if (res.status) {
          return message.info(res.msg);
        }
        return message.error(res.msg);
      },
    });
  };

  editUser = row => {
    const { dispatch } = this.props;
    dispatch({
      type: 'robotManage/editUser',
      payload: { disabled: !row.disabled, robotId: row.id },
      callback: res => {
        if (!res.code) {
          message.info(res.msg);
          this.setState({ visible: false });
          this.getUsers();
        } else {
          this.setState({
            auth: false,
          });
          // message.error(res.msg);
        }
      },
    });
  };

  queryUser = row => {
    const { dispatch } = this.props;
    this.setState({ visible: true, isEdit: true, loading: true });
    dispatch({
      type: 'robotManage/queryUser',
      payload: { userId: row._id },
      callback: res => {
        this.setState({ userInfo: res, loading: false });
      },
    });
  };

  setSearch = val => {
    this.setState(
      {
        searchText: val,
        page: 1,
      },
      () => {
        this.getUsers();
      }
    );
  };

  setClassName = record => {
    return record.disabled ? styles.grey : '';
  };

  todo = row => {
    const { currentUser } = this.props;
    if (currentUser.nick === row.nick) {
      return true;
    }
  };

  sty = row => {
    const { currentUser } = this.props;
    if (currentUser.nick === row.nick) {
      return { marginRight: 5 };
    } else {
      return { marginRight: 5, color: '#fff' };
    }
  };

  qwe = row => {
    const { currentUser } = this.props;
    if (currentUser.nick === row.nick) {
      return { marginRight: 5 };
    } else {
      return { marginRight: 5 };
    }
  };

  getRobotToken = e => {
    let { guest } = e;
    const { dispatch } = this.props;
    if(e.disabled) {
      message.error("停用状态的用户无法查看");
    }else {
      this.setState({isLoading:true},() => {
        dispatch({
          type: 'robotManage/changeUserByAdmin',
          payload: { name: guest },
          callback: res => {
            this.setState({
              isLoading: false,
            });
          },
        });
      })
    }
  };

  render() {
    const { notices, tableLoading, page, total, pageSize, userInfo, isEdit, loading,isLoading } = this.state;
    return (
      <Spin spinning={isLoading}>
        <Suspense fallback={<PageLoading />}>
          <PageHeaderWrapper>
            <Card bordered={false}>
              <div
                style={{ marginBottom: 10, borderBottom: '1px solid lightgrey', paddingBottom: 10 }}
              >
                <span
                  style={{
                    fontSize: 16,
                    color: '#000',
                    borderLeft: '5px solid #13c2f3',
                    paddingLeft: 10,
                  }}
                >
                  机器人管理 ({total})
                </span>
              </div>
              <Row style={{ marginBottom: 10 }}>
                <Col span={4}>
                  <Button
                    type="primary"
                    icon="plus"
                    htmlType="button"
                    style={{ marginRight: 5 }}
                    onClick={this.showModal}
                  >
                    添加
                  </Button>
                </Col>
                <Col offset={16} span={4}>
                  <Search placeholder="请输入账户名" onSearch={value => this.setSearch(value)} />
                </Col>
              </Row>
              <div>
                <Table
                  rowClassName={this.setClassName}
                  columns={this.columns}
                  dataSource={notices}
                  rowClassName={this.setClassName}
                  rowKey="id"
                  loading={this.state.tableLoading}
                  pagination={{
                    // 分页
                    total,
                    pageSize, // 显示几条一页
                    // defaultPageSize: page, // 当前页
                    showSizeChanger: true, // 是否显示可以设置几条一页的选项
                    showQuickJumper: true,

                    // onChange: this.onChangeForPage,
                    onShowSizeChange: this.onShowSizeChangeForPage,
                  }}
                  // loading={tableLoading}
                />
              </div>

              <CollectionCreateForm
                wrappedComponentRef={this.saveFormRef}
                visible={this.state.visible}
                onCancel={this.handleCancel}
                onCreate={this.handleCreate}
                userInfo={userInfo}
                isEdit={isEdit}
                loading={loading}
              />
            </Card>
          </PageHeaderWrapper>
        </Suspense>
      </Spin>
    );
  }
}

export default connect(({ user }) => ({
  currentUser: user.currentUser,
}))(RobotManage);
